package com.example.javaproject.controller;

import com.example.javaproject.common.R;
import com.example.javaproject.entity.*;
import com.example.javaproject.service.*;
import com.example.javaproject.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/admin")
public class AdministratorController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private PositionService positionService;
    
    @Autowired
    private PositionApplicationService positionApplicationService;
    
    @Autowired
    private SalaryService salaryService;

    @Autowired
    private AdministratorService administratorService;

    @GetMapping("/info")
    public R getAdminInfo(@RequestHeader("Authorization") String authHeader) {
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return R.error("未登录");
        }
        String token = authHeader.substring(7);
        Claims claims = JwtUtil.parseToken(token);
        Integer userId = claims.get("userId", Integer.class);
        if (userId == null) {
            return R.error("无效token");
        }

        // 获取管理员信息
        Administrator admin = administratorService.getByUserId(userId);
        if (admin == null) {
            return R.error("未找到管理员信息");
        }

        // 获取用户信息
        User user = userService.getById(userId);
        if (user == null) {
            return R.error("未找到用户信息");
        }

        // 组装返回数据
        Map<String, Object> data = new HashMap<>();
        data.put("name", admin.getName());
        data.put("adminId", admin.getId());
        data.put("username", user.getUsername());
        data.put("mail", user.getMail());
        data.put("phone", user.getPhone());
        data.put("password", user.getPassword());

        return R.ok(data);
    }

    @PutMapping("/info")
    public R updateAdminInfo(@RequestHeader("Authorization") String authHeader, @RequestBody Map<String, String> data) {
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return R.error("未登录");
        }
        String token = authHeader.substring(7);
        Claims claims = JwtUtil.parseToken(token);
        Integer userId = claims.get("userId", Integer.class);
        if (userId == null) {
            return R.error("无效token");
        }

        // 获取管理员信息
        Administrator admin = administratorService.getByUserId(userId);
        if (admin == null) {
            return R.error("未找到管理员信息");
        }

        // 获取用户信息
        User user = userService.getById(userId);
        if (user == null) {
            return R.error("未找到用户信息");
        }

        // 更新用户信息
        if (data.containsKey("username")) {
            user.setUsername(data.get("username"));
        }
        if (data.containsKey("password") && !data.get("password").isEmpty()) {
            user.setPassword(data.get("password")); // 注意：实际应用中需要加密
        }
        if (data.containsKey("mail")) {
            user.setMail(data.get("mail"));
        }
        if (data.containsKey("phone")) {
            user.setPhone(data.get("phone"));
        }

        // 保存更新
        boolean success = userService.updateById(user);
        if (!success) {
            return R.error("更新失败");
        }

        return R.ok("更新成功");
    }

    @GetMapping("/dashboard-stats")
    public R getDashboardStats(@RequestHeader("Authorization") String authHeader) {
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return R.error("未登录");
        }
        String token = authHeader.substring(7);
        Claims claims = JwtUtil.parseToken(token);
        Integer userId = claims.get("userId", Integer.class);
        Integer role = claims.get("role", Integer.class);
        if (userId == null) {
            return R.error("无效token");
        }
        
        // 验证是否为管理员角色
        if (role == null || role != 0) { // 0是管理员角色
            return R.error("权限不足，仅管理员可查看此统计");
        }
        
        // 1. 获取总用户数（所有未删除的用户）
        long totalUsers = userService.lambdaQuery()
                .eq(User::getIsDeleted, 0)
                .count();
        
        // 2. 获取活跃岗位数量（status=0表示招聘中）
        long activePositions = positionService.lambdaQuery()
                .eq(Position::getStatus, 0)
                .eq(Position::getIsDeleted, 0)
                .count();
        
        // 3. 获取待处理申请数量（status=0表示待审核）
        long pendingApplications = positionApplicationService.lambdaQuery()
                .eq(PositionApplication::getStatus, 0)
                .eq(PositionApplication::getIsDeleted, 0)
                .count();
        
        // 4. 获取本月发放工资（当前月份的工资记录，状态为已通过，以发放时间为准）
        java.time.LocalDateTime now = java.time.LocalDateTime.now();
        java.time.LocalDateTime startOfMonth = now.withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
        java.time.LocalDateTime endOfMonth = now.withDayOfMonth(now.toLocalDate().lengthOfMonth()).withHour(23).withMinute(59).withSecond(59).withNano(999999999);
        
        List<Salary> monthSalaries = salaryService.lambdaQuery()
                .eq(Salary::getStatus, 1) // 1表示已通过/成功发放
                .eq(Salary::getIsDeleted, 0)
                .ge(Salary::getUpdateTime, startOfMonth) // 使用update_time作为发放时间
                .le(Salary::getUpdateTime, endOfMonth)
                .list();
        
        double totalSalary = 0.0;
        for (Salary salary : monthSalaries) {
            if (salary.getTotalSalary() != null) {
                totalSalary += salary.getTotalSalary().doubleValue();
            }
        }
        
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalUsers", totalUsers);
        stats.put("activePositions", activePositions);
        stats.put("pendingApplications", pendingApplications);
        stats.put("monthlySalary", totalSalary);
        
        return R.ok(stats);
    }
} 